package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.util.NumberUtils;
import com.cskaoyan.order.biz.callback.SendEmailCallback;
import com.cskaoyan.order.biz.callback.TransCallback;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dto.CartProductDto;
import com.cskaoyan.order.utils.GlobalIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.omg.PortableInterceptor.ObjectReferenceFactory;
import org.redisson.api.RBucket;
import org.redisson.api.RKeys;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;

/**
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {



    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private GlobalIdGeneratorUtil globalIdGeneratorUtil;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    RedissonClient redissonClient;


    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {

        //初始化订单

        //向下转型
        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        //插入订单表
        Order order = new Order();
        //RBucket<String> orderId = redissonClient.getBucket("order_Id");
        // if (orderId != null) {
        //     String choiceId = globalIdGeneratorUtil.getNextSeq("order_Id", 1);
        //     if (choiceId.compareTo(orderId.get()) < 0)
        // }


        //已修改为发号器，测试成功
        String orderId = globalIdGeneratorUtil.getNextSeq("order_Id",1);

        // 后面修改为发号器
        // String orderId = UUID.randomUUID().toString();
        order.setOrderId(orderId);
        order.setUserId(createOrderContext.getUserId());
        order.setBuyerNick(createOrderContext.getBuyerNickName());
        order.setPayment(createOrderContext.getOrderTotal());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        //设置订单状态
        order.setStatus(OrderConstants.ORDER_STATUS_INIT);

        orderMapper.insert(order);

        List<Long> buyproductIds = new ArrayList<>();
        //插入订单商品关联表
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto cartProductDto : cartProductDtoList) {

            OrderItem orderItem = new OrderItem();
            String orderItemId = globalIdGeneratorUtil.getNextSeq("order_Item_Id",1);
            //String orderItemId = UUID.randomUUID().toString();

            orderItem.setId(orderItemId);
            orderItem.setItemId(cartProductDto.getProductId());
            orderItem.setOrderId(orderId);
            orderItem.setNum(cartProductDto.getProductNum().intValue());
            orderItem.setPrice(cartProductDto.getSalePrice().doubleValue());
            orderItem.setTitle(cartProductDto.getProductName());
            orderItem.setPicPath(cartProductDto.getProductImg());
            BigDecimal total = cartProductDto.getSalePrice().multiply(new BigDecimal(cartProductDto.getProductNum()));
            //总价，需要计算一下  售价 * 数量
            orderItem.setTotalFee(total.doubleValue());
            //已经锁定库存了
            orderItem.setStatus(1);

            buyproductIds.add(cartProductDto.getProductId());

            orderItemMapper.insert(orderItem);

        }
        //生成订单之后
        createOrderContext.setOrderId(orderId);
        createOrderContext.setBuyProductIds(buyproductIds);

        return true;
    }





}
